<?php
namespace System\Controller;

use Common\Controller\AdminbaseController;

class AdminUserController extends AdminbaseController{

	protected $admin_model,$admin_role_model;

	public function _initialize() {
		parent::_initialize();
		$this->admin_model = D("SystemAdmin");
		$this->admin_role_model = D("SystemAdminRole");
	}

	// 管理员列表
	public function index(){
		/**搜索条件**/
		$user_login = I('request.user_login');
		$user_email = trim(I('request.user_email'));
		if($user_login){
			$where['user_login'] = array('like',"%$user_login%");
		}

		if($user_email){
			$where['user_email'] = array('like',"%$user_email%");;
		}

		$count=$this->admin_model->where($where)->count();
		$page = $this->page($count, 20);
		$users = $this->admin_model
			->where($where)
			->order("create_time DESC")
			->limit($page->firstRow, $page->listRows)
			->select();
		$roles_src=$this->admin_role_model->select();
		foreach ($roles_src as $r){
			$roleid=$r['id'];
			$roles["$roleid"]=$r;
		}
		$this->assign("page", $page->show('Admin'));
		$this->assign("roles",$roles);
		$this->assign("users",$users);
		$this->display();
	}

	// 管理员添加
	public function add(){
		$roles=M('system_admin_role')->where(array('status' => 1))->order("id DESC")->select();
		$this->assign("roles",$roles);
		$this->display();
	}

	// 管理员添加提交
	public function add_post(){
		if(IS_POST){
			if(!empty($_POST['role_id']) && is_array($_POST['role_id'])){
				$role_ids=$_POST['role_id'];
				unset($_POST['role_id']);
				if ($this->admin_model->create()!==false) {
					$result=$this->admin_model->add();
					if ($result!==false) {
						$role_user_model=M("SystemAdminRoleUser");
						foreach ($role_ids as $role_id){
							if(sp_get_current_admin_id() != 1 && $role_id == 1){
								$this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
							}
							$role_user_model->add(array("role_id"=>$role_id,"user_id"=>$result));
						}
						$role_user_model->add(array("role_id"=>1,"user_id"=>$result));
						$this->success("添加成功！", U("System/AdminUser/index"));
					} else {
						$this->error("添加失败！");
					}
				} else {
					$this->error($this->admin_model->getError());
				}
			}else{
				$this->error("请为此用户指定角色！");
			}

		}
	}

	// 管理员编辑
	public function edit(){
		$id = I('get.id',0,'intval');
		$roles=M('system_admin_role')->where(array('status' => 1))->order("id DESC")->select();
		$this->assign("roles",$roles);
		$role_user_model=M("SystemAdminRoleUser");
		$role_ids=$role_user_model->where(array("user_id"=>$id))->getField("role_id",true);
		$this->assign("role_ids",$role_ids);

		$user=$this->admin_model->where(array("id"=>$id))->find();
		$this->assign($user);
		$this->display();
	}

	// 管理员编辑提交
	public function edit_post(){
		if (IS_POST) {
			if(!empty($_POST['role_id']) && is_array($_POST['role_id'])){
				if(empty($_POST['user_pass'])){
					unset($_POST['user_pass']);
				}
				$role_ids = I('post.role_id/a');
				unset($_POST['role_id']);
				if ($this->admin_model->create()!==false) {
					$result=$this->admin_model->save();
					if ($result!==false) {
						$uid = I('post.id',0,'intval');
						$role_user_model=M("SystemAdminRoleUser");
						$role_user_model->where(array("user_id"=>$uid))->delete();
						foreach ($role_ids as $role_id){
							if(sp_get_current_admin_id() != 1 && $role_id == 1){
								$this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
							}
							$role_user_model->add(array("role_id"=>$role_id,"user_id"=>$uid));
						}
						$this->success("保存成功！");
					} else {
						$this->error("保存失败！");
					}
				} else {
					$this->error($this->admin_model->getError());
				}
			}else{
				$this->error("请为此用户指定角色！");
			}

		}
	}

	// 管理员删除
	public function delete(){
		$id = I('get.id',0,'intval');
		if($id==1){
			$this->error("最高管理员不能删除！");
		}

		if ($this->admin_model->delete($id)!==false) {
			M("SystemAdminRoleUser")->where(array("user_id"=>$id))->delete();
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	// 管理员个人信息修改
	public function userinfo(){
		$id=sp_get_current_admin_id();
		$user=$this->admin_model->where(array("id"=>$id))->find();
		$this->assign($user);
		$this->display();
	}

	// 管理员个人信息修改提交
	public function userinfo_post(){
		if (IS_POST) {
			$_POST['id']=sp_get_current_admin_id();
			$create_result=$this->admin_model
			->field("id,user_nicename,sex,birthday,user_url,signature")
			->create();
			if ($create_result!==false) {
				if ($this->admin_model->save()!==false) {
					$this->success("保存成功！");
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->admin_model->getError());
			}
		}
	}

	// 停用管理员
	public function ban(){
		$id = I('get.id',0,'intval');
		if (!empty($id)) {
			$result = $this->admin_model->where(array("id"=>$id,"user_type"=>1))->setField('user_status','0');
			if ($result!==false) {
				$this->success("管理员停用成功！", U("AdminUser/index"));
			} else {
				$this->error('管理员停用失败！');
			}
		} else {
			$this->error('数据传入失败！');
		}
	}

	// 启用管理员
	public function cancelban(){
		$id = I('get.id',0,'intval');
		if (!empty($id)) {
			$result = $this->admin_model->where(array("id"=>$id,"user_type"=>1))->setField('user_status','1');
			if ($result!==false) {
				$this->success("管理员启用成功！", U("AdminUser/index"));
			} else {
				$this->error('管理员启用失败！');
			}
		} else {
			$this->error('数据传入失败！');
		}
	}


// 用户头像api
	public function avatar(){
		$users_model=D("SystemAdmin");
		$id=I("get.id",0,"intval");

		$find_user=$users_model->field('avatar')->where(array("id"=>$id))->find();

		$avatar=$find_user['avatar'];
		$avatar=preg_replace("/^avatar\//", '', $avatar);//2.2以后头像路径统一以avatar/开头
		$should_show_default=false;

		if(empty($avatar)){
			$should_show_default=true;
		}else{
			if(strpos($avatar,"http")===0){
				header("Location: $avatar");exit();
			}else{
				$avatar_dir=C("UPLOADPATH")."avatar/";
				$avatar=$avatar_dir.$avatar;
				if(file_exists($avatar)){
					$imageInfo = getimagesize($avatar);
					if ($imageInfo !== false) {
					    $fp=fopen($avatar,"r");
					    $file_size=filesize($avatar);
						$mime=$imageInfo['mime'];
						header("Content-type: $mime");
						header("Accept-Length:".$file_size);
						$buffer=1024*64;
						$file_count=0;
						//向浏览器返回数据
						while(!feof($fp) && $file_count<$file_size){
						    $file_content=fread($fp,$buffer);
						    $file_count+=$buffer;
						    echo $file_content;
						    flush();
						    ob_flush();
						}
						fclose($fp);
					}else{
						$should_show_default=true;
					}
				}else{
					$should_show_default=true;
				}
			}


		}

		if($should_show_default){
			$imageInfo = getimagesize("public/images/headicon.png");
			if ($imageInfo !== false) {
				$mime=$imageInfo['mime'];
				header("Content-type: $mime");
				echo file_get_contents("public/images/headicon.png");
			}

		}
		exit();

	}


	// 密码修改
	public function password(){
		$this->display('password');
	}

	// 密码修改提交
	public function password_post(){
		if (IS_POST) {
			if(empty($_POST['old_password'])){
				$this->error("原始密码不能为空！");
			}
			if(empty($_POST['password'])){
				$this->error("新密码不能为空！");
			}
			$user_obj = M('SystemAdmin');
			$uid=sp_get_current_admin_id();
			$admin=$user_obj->where(array("id"=>$uid))->find();
			$old_password=I('post.old_password');
			$password=I('post.password');
			if(sp_compare_password($old_password,$admin['user_pass'])){
				if($password==I('post.repassword')){
					if(sp_compare_password($password,$admin['user_pass'])){
						$this->error("新密码不能和原始密码相同！");
					}else{
						$data['user_pass']=sp_password($password);
						$data['id']=$uid;
						$r=$user_obj->save($data);
						if ($r!==false) {
							$this->success("修改成功！");
						} else {
							$this->error("修改失败！");
						}
					}
				}else{
					$this->error("密码输入不一致！");
				}

			}else{
				$this->error("原始密码不正确！");
			}
		}
	}



}